from datetime import datetime
import time

class API_Controller:
    def __init__(self,lph,secs=3600,interval=2):
        #lph represent limit perhour
        self.lph = lph 
        self.count = 0
        #ts represents timestamp
        self.ts = datetime.now()
        #define the "per hour"
        self.secs = secs
        self.interval = interval

    def add(self):

        print "in add, current count"+str(self.count)+"\n"

        if self.count == 0:
            self.ts = datetime.now() 
            self.count = 1
        else:
            if self.count < self.lph-1:
                self.count = self.count + 1
            else:
                #if reaches here, means the invocation now has exceeds the lhp
                now = datetime.now()
                diff = now - self.ts
                if diff.seconds > self.secs:
                    #here means it is ok to invoke this time because it is acturally in another time period, reset ts
                    self.ts = datetime.now()
                    self.count = 1
                else:
                    #here means it exceeds lph
                    print "hang!\n"
                    print "exceeds maximum, count:"+str(self.count)+" start time:"+str(self.ts)+" now:"+str(now)+" diff:"+str(diff.seconds)+"\n"
                    sleep_time = self.secs - diff.seconds + 1 + self.interval
                    time.sleep( sleep_time )
                    now = datetime.now()
                    diff = now - self.ts
                    while diff.seconds <= self.secs:
                        time.sleep(self.interval)
                        now = datetime.now()
                        diff = now-self.ts
                    print "awake!\n"
                    print "now:"+str(now)+" diff:"+str(diff.seconds)+"\n"
                    self.ts = datetime.now()
                    self.count = 1

    
                
            
        
        

